package com.xunwulian.web.innerservice;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xunwulian.api.iface.RoleAPI;
import com.xunwulian.base.constant.BillStatus;
import com.xunwulian.base.constant.ConstantBean;
import com.xunwulian.base.constant.RoleType;
import com.xunwulian.base.dao.*;
import com.xunwulian.base.entity.*;
import com.xunwulian.base.util.DateStyle;
import com.xunwulian.base.util.DateUtil;
import com.xunwulian.base.util.StringUtil;
import com.xunwulian.base.util.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class InnerBillService {

    protected static final Logger logger = LoggerFactory.getLogger(InnerBillService.class);

    @Autowired
    private BillDao billDao;

    @Autowired
    private CardNodeDao cardNodeDao;

    @Autowired
    private BillDetailDao billDetailDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private CardInfoDao cardInfoDao;

    @Reference
    private RoleAPI roleAPI;

    public List<BillEntity> getBillList(String roleId,
                                        String userId,
                                        String appId,
                                        String userName,
                                        String searchKey,
                                        Page page) {

        // 列出CardInfo列表
        if (UserUtil.isAdmin(roleId)) {

            return billDao.listPageByAdmin(page, searchKey, userName, null);
        } else if (UserUtil.isSubAdmin(roleId)) {

            return billDao.listPageByAdmin(page, searchKey, userName, appId);

        } else if (RoleType.COOPER.getType().equals(roleAPI.getRoleTypeById(roleId).getType())) {

            return billDao.listPageByUserId(page, userId, searchKey);

        }

        return null;
    }


    /**
     * 按用户生成账单
     *
     * @param billMonth 格式为 2017-05
     */

    public void generateByUserId(String billMonth, String userId) {

        // 获取某个客户的所有卡段号
        List<CardNodeEntity> cardNodes = cardNodeDao.getByUserId(userId);

        // 总的收费卡数
        long totalBillCard = 0;
        // 总的消费金额
        double totalFee = 0;
        // 号段数
        int cardNodeNum = 0;

        // 要出账单的月份
        Date billDate = DateUtil.StringToDate(billMonth, DateStyle.YYYY_MM);

        // 清理历史数据
        List<BillEntity> oldBillList = billDao.listByUserIdAndMonth(userId, billDate);
        if (oldBillList != null && oldBillList.size() > 0) {
            oldBillList.forEach(p -> {
                billDetailDao.deleteByBillId(p.getBillId());
            });
        }
        billDao.deleteByUserIdAndMonth(userId, billDate);


        String billId = StringUtil.createIdentity(32);
        for (CardNodeEntity cardNode : cardNodes) {

            if (cardNode.getActiveNum() > 0) {

                List<CardInfoEntity> cardInfoList = cardInfoDao.getListByRange(String.valueOf(cardNode.getStart()),
                        String.valueOf(cardNode.getEnd()));

                // 到期日期为账单日的，求和
                double fee = cardInfoList.stream().filter(p -> p.getUserEndDate().equals(billDate)).mapToDouble(p -> p.getUserPrice()).sum();

                long billCardNum = cardInfoList.stream().filter(p -> p.getUserEndDate().equals(billDate)).count();

                BillDetailEntity bde = new BillDetailEntity(billId,
                        StringUtil.createIdentity(32),
                        cardNode.getAppId(),
                        cardNode.getUserId(),
                        cardNode.getSubUserId(),
                        cardNode.getStart(),
                        cardNode.getEnd(),
                        billCardNum,
                        cardNode.getActiveNum(),
                        cardNode.getUserPkg(),
                        cardNode.getUserPrice(),
                        fee,
                        BillStatus.UNPAID.getType());

                billDetailDao.insert(bde);

                totalFee += fee;
                totalBillCard += billCardNum;
                cardNodeNum++;
            }

        }

        logger.info("userId:" + userId + ", 账单日期：" + DateUtil.DateToString(billDate, DateStyle.YYYY_MM_DD)
                + "， 金额：" + totalFee);


        User user = userDao.getByUid(userId);

        BillEntity be = new BillEntity(billDate,
                billId,
                userId,
                user.getUSERNAME(),
                totalFee,
                totalBillCard,
                totalFee > 0 ? BillStatus.UNPAID.getType() : BillStatus.PAID.getType(),
                cardNodeNum);

        billDao.insert(be);
    }

}
